package com.aispeech.task.api.handler.error;

import com.aispeech.task.api.data.enums.Errors;
import com.aispeech.task.api.exceptions.ParamsError;
import com.aispeech.task.api.exceptions.StaticError;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.reactive.error.DefaultErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.server.ResponseStatusException;

import java.util.LinkedHashMap;
import java.util.Map;

@Slf4j
@Component
public class ErrorAttributes extends DefaultErrorAttributes {
    public ErrorAttributes() {
        super(false);
    }

    @Override
    public Map<String, Object> getErrorAttributes(ServerRequest request, boolean includeStackTrace) {
        return assembleError(request);
    }

    private Map<String, Object> assembleError(ServerRequest request) {
        Map<String, Object> errorAttributes = new LinkedHashMap<>();
        Throwable error = getError(request);
        if (error instanceof ResponseStatusException) {
            errorAttributes.put("errno", ((ResponseStatusException) error).getStatus().value());
            errorAttributes.put("error", error.getMessage());
        } else if (error instanceof ParamsError) {
            ParamsError err = (ParamsError) error;
            errorAttributes.put("errno", err.getError().getErrorCode());
            errorAttributes.put("error", err.getMessage());
        } else if (error instanceof StaticError) {
            Errors err = ((StaticError) error).getError();
            errorAttributes.put("errno", err.getErrorCode());
            errorAttributes.put("error", err.getErrorDesc());
        } else {
            errorAttributes.put("errno", HttpStatus.INTERNAL_SERVER_ERROR.value());
            errorAttributes.put("error", "INTERNAL SERVER ERROR");
            log.error("assembleError", error);
        }
        return errorAttributes;
    }
}
